class Product < ApplicationRecord
  has_and_belongs_to_many :tags, class_name: 'Attribute', join_table: 'products_attributes'

  scope :search_import, -> { includes(:tags).where(published: true) }

  # 默认排序
  scope :default_order, -> {[{_score: {order: 'desc'}}, {display_order: {order: 'desc'}}]}

  # 价格升序
  scope :price_asc_order, -> {[{price: {order: 'asc'}}, {_score: {order: 'desc'}}, {display_order: {order: 'desc'}}]}

  #价格降序
  scope :price_desc_order, -> {[{price: {order: 'desc'}}, {_score: {order: 'desc'}}, {display_order: {order: 'desc'}}]}

  # 默认条件，今天要在display time内
  scope :default_where, -> { [{range: {display_start_at: {lte: "now/d"}}},
                              {range: {display_end_at: {gte: "now/d"}}}] }

  PRICE_RANGE = {1 => {lt: 10}, 2 => {gte: 10, lt: 100}, 3 => {gte: 100, lt: 200}, 4 => {gte: 200, lt: 500}, 5 => {gte: 500}}

  # searchkick
  searchkick merge_mappings: true, mappings: {
    properties: {
      name: {
        type: 'keyword',
        fields: {
          analyzer: {
            type: 'text'
          }
        }
      },
      store_code: { type: 'keyword' },
      full_description: { type: 'text' },
      display_order: { type: 'integer' },
      display_start_at: { type: 'date' },
      display_end_at: { type: 'date' },
      price: {
        type: 'scaled_float',
        "scaling_factor": 100
      },
      attrs: {
        type: 'nested',
        properties: {
          name: {
            type: 'keyword',
            fields: {
              analyzer:{
                type: 'text'
              }
            }
          }
        }
      }
    }
  }

  def search_data
    {
      name: name,
      store_code: store_code,
      full_description: full_description,
      display_order: display_order,
      display_start_at: display_start_at,
      display_end_at: display_end_at,
      price: price,
      attrs: tags.map { |tag| { name: tag.name } }
    }
  end

  def should_index?
    # 只有published才创建索引
    published
  end

  # 商品检索
  def self.get_query_all_fields(params)
    bool_conn = {}
    # 全商品检索
    search_where = [{match_all: {}}]
    # 过滤器
    filter = []
    #后过滤器
    post_filter = []
    # 全字段检索
    if params.has_key? "search1"
      search_where = [{bool: {should:
                               [
                                 {multi_match: {query: params[:search1][:search_word],
                                               fields: %w(name.analyzer store_code full_description)}},
                                 {nested: {path: 'attrs', query: {match: {"attrs.name.analyzer": params[:search1][:search_word]}}}}
                               ]}}]
    elsif params.has_key? "search2"
      detail_search = [{match_all: {}}]
      if (p_name = params[:search2][:product_name]).present?
        detail_search << {match: {"name.analyzer": p_name}}
      end

      #价格start要大于等于price
      if (price_s = params[:search2][:price_start]).present?
        detail_search << {range: {price: {gte: price_s}}}
      end

      #价格end要小于等于price
      if (price_end = params[:search2][:price_end]).present?
        detail_search << {range: {price: {lte: price_end}}}
      end

      if (code = params[:search2][:store_code]).present?
        detail_search << {match: {store_code: code}}
      end

      search_where = [{bool: {must: detail_search}}]
    end
    search_where += default_where
    (params["tags"] || []).each do |key, value|
      next if value.blank?
      filter << {nested: {path: 'attrs', query:{match: {'attrs.name': value}}}}
    end
    # tag标签分组，显示各个tag下的件数
    aggs_conn = {tags: {nested: {path: 'attrs'}, aggs: {t_name: {terms: {field: 'attrs.name', order: {_count: 'desc'}, size: 10}}}}}
    # 价格分组
    price_ranges = []
    # 低于10
    price_ranges << {key: '低于10', to: 10}
    # 10 - 100
    price_ranges << {key: '10到100', from: 10, to: 100}
    # 100 - 200
    price_ranges << {key: '100到200', from: 100, to: 200}
    # 200 - 500
    price_ranges << {key: '200到500', from: 200, to: 500}
    # 500及其以上
    price_ranges << {key: '200到500', from: 500}
    aggs_conn["price_ranges"] = {range: {field: 'price', ranges: price_ranges}}

    #价格range筛选
    if (range = params[:price_range].to_i) && PRICE_RANGE[range].present?
      price_range = PRICE_RANGE[range]
      post_filter << {range: {price: price_range}}
    end
    bool_conn[:bool] = {must: search_where}

    bool_conn[:bool][:filter] = filter if filter.present?
    # 排序
    data_order = default_order if params[:data_order].to_i == 0
    data_order = price_asc_order if params[:data_order].to_i == 1
    data_order = price_desc_order if params[:data_order].to_i == 2
    data_order ||= default_order

    query_body = {query: bool_conn, sort: data_order, aggs: aggs_conn}
    query_body[:post_filter] = {bool: {must: post_filter}} if post_filter.present?
    search body: query_body, per_page: 10, page: params[:page] || 1
  end


end
